package org.example.servicelogin.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.example.model.manage.bean.po.security.MyUserDetails;
import org.example.model.manage.security.SecurityConstants;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Order(1)
public class GatewayUserPropagationFilter implements Filter {

    private final ObjectMapper objectMapper;

    public GatewayUserPropagationFilter(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String path = req.getRequestURI();
        if ("/login".equals(path)) {
            chain.doFilter(request, response);
            return;
        }
        String userId = req.getHeader(SecurityConstants.HEADER_USER_ID);
        String userInfo = req.getHeader(SecurityConstants.HEADER_USER_INFO);
        if (userId != null && userInfo != null) {
            try {
                MyUserDetails details = objectMapper.readValue(userInfo, MyUserDetails.class);
                request.setAttribute(SecurityConstants.ATTR_USER_ID, userId);
                request.setAttribute(SecurityConstants.ATTR_USER_DETAILS, details);
                // Set authenticated principal so Spring Security recognizes authentication
                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(details, null, details.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authentication);
            } catch (Exception ignored) { }
        }
        chain.doFilter(request, response);
    }
}
